using System.Collections.Generic;
using CardGameObject.Common;
using Common;
using Entity;
using Mapper;
using TMPro;
using UnityEngine;

namespace CardGameObject.CollectScene
{
    public class CollectManager : MonoBehaviour
    {
        // 卡牌位置列表
        public List<GameObject> CollectPositionList {  get;set; } = new();
        // 展示的卡牌列表
        public Dictionary<long , GameObject> CollectCardList {  get;set; } = new();
        
        // 展示的卡牌数量
        private const int COLLECT_CARD_NUMBER = 8;

        // 单例模式
        private static CollectManager instance;

        // 当前正在操作的卡组ID
        private static long deckId;
        
        // 当前正在查看的卡片
        private CollectCardVO currentCard;

        // 场景组件
        public GameObject ScrollContent;
        public GameObject CollectDeckCardPrefab;
        public GameObject CollectCardPrefab;
        public GameObject DustDisplay;
        public Canvas CardDetailCanvas;
        public GameObject CardDetailObject;
        public TextMeshProUGUI ResolveDustNum;
        public TextMeshProUGUI CompoundDustNum;
        
        // 展示使用的分页参数
        private int current = 1;
        private const int PAGE_SIZE = 8;

        // 卡组中的卡牌信息，Key为卡牌ID，Value为卡牌数量
        private Dictionary<long, int> DeckCardList { get; set; } = new();
        // 卡组中的卡牌信息，Key为卡牌ID，Value为该卡牌在场景中的游戏物体
        private Dictionary<long, GameObject> DeckCardObjectList { get; set; } = new();

        private void Awake()
        {
            if (!instance)
            {
                instance = this;
            }
        }

        private void Start()
        {
            CardDetailCanvas.enabled = false;
            // 获取卡牌展示位置列表
            for (int i = 1; i <= COLLECT_CARD_NUMBER; i++)
            {
                GameObject collectPosition = GameObject.Find("CollectPosition_" + i);
                CollectPositionList.Add(collectPosition);
            }
            
            // 获取卡组ID
            deckId = PlayerPrefs.GetInt("DeckId");
            CardMapper cardMapper = new CardMapper();
            List<CollectCardVO> cardList = cardMapper.ListCollectCardVOByDeckId(deckId);
            // 展示卡组内容
            foreach (CollectCardVO collectCardVO in cardList)
            {
                GameObject collectDeckCard = Instantiate(CollectDeckCardPrefab, ScrollContent.transform);
                collectDeckCard.transform.parent = ScrollContent.transform;
                CollectDeckCard card = collectDeckCard.GetComponent<CollectDeckCard>();
                // 设置卡牌信息
                card.SetCardInfo(collectCardVO.CardId, collectCardVO.CardName, collectCardVO.CardCount);
                DeckCardList.Add(collectCardVO.CardId, collectCardVO.CardCount);
                DeckCardObjectList.Add(collectCardVO.CardId, collectDeckCard);
            }
            cardMapper.CloseConnection();
            
            // 展示卡牌
            ShowCollectCards(current, PAGE_SIZE);
        }
        
        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.Escape))
            {
                CardDetailCanvas.enabled = false;
            }
        }

        public static long GetEditDeckId()
        {
            if (deckId != 0) return deckId;
            Debug.Log("无法获取传入的卡组ID");
            return 0;
        }

        public static CollectManager GetInstance()
        {
            if (!instance)
            {
                Debug.LogError("请不要在非Collect场景获取Collect对象");
            }
            return instance;
        }

        private GameObject CreateObjectOnPosition(GameObject position)
        {
            Transform positionTransform = position.transform;
            Vector3 positionPosition = positionTransform.position;
            GameObject newCard = Instantiate(CollectCardPrefab, positionPosition, positionTransform.rotation);
            return newCard;
        }

        private void ShowCollectCards(int current, int pageSize)
        {
            // 清空之前的展示结果
            ClearCollectCards();
            // 计算分页参数，遍历数据
            this.current = current <= 0 ? 1 : current;
            CardMapper collectCardMapper = new CardMapper();
            List<CollectCardVO> collectCards = collectCardMapper.ListCollectCardVOPageByUserId(1, current, pageSize);
            // 进行卡牌数据设置以及文本设置
            for (int i = 0; i < collectCards.Count; i++)
            {
                GameObject card = CreateObjectOnPosition(CollectPositionList[i]);
                CollectCard collectCard = card.GetComponent<CollectCard>();
                collectCard.Card = collectCards[i];
                // 判断卡组中是否含有该卡牌
                if (DeckCardList.ContainsKey(collectCards[i].CardId))
                {
                    // 如果卡组中有该卡牌，则让其数量减去卡组中该卡牌的数量
                    int count = DeckCardList[collectCards[i].CardId];
                    collectCard.Card.CardCount -= count;
                }
                collectCard.SetCardInfo();
                // 将卡牌加入到List中管理
                CollectCardList.Add(collectCards[i].CardId, card);
            }
        }

        public void OnShowNextPageCards()
        {
            if (CollectCardList.Count < 8)
            {
                return;
            }
            current += 1;
            ShowCollectCards(current, PAGE_SIZE);
        }

        public void OnShowPrePageCards()
        {
            if (current <= 1)
            {
                return;
            }
            current -= 1;
            ShowCollectCards(current, PAGE_SIZE);
        }

        /// <summary>
        /// 分解指定卡牌
        /// </summary>
        /// <param name="card">要分解的卡牌</param>
        public void OnResolveCard()
        {
            
            if (currentCard.CardCount <= 0)
            {
                Debug.Log("卡牌数量小于1张，不能分解");
                return;
            }
            currentCard.CardCount -= 1;
            int dustNum = 0;
            if (currentCard.CardRarity == (int)CardRarityEnum.N)
            {
                dustNum = 10;
            }else if (currentCard.CardRarity == (int)CardRarityEnum.R)
            {
                dustNum = 30;
            }else if (currentCard.CardRarity == (int)CardRarityEnum.SR)
            {
                dustNum = 100;
            }else if (currentCard.CardRarity == (int )CardRarityEnum.UR)
            {
                dustNum = 1000;
            }
            UserMapper userMapper = new UserMapper();
            // 修改尘的数量展示
            ItemDisplay itemDisplay = DustDisplay.GetComponent<ItemDisplay>();
            User user = new User();
            // TODO 修改为当前登录的玩家
            user.UserId = 1;
            user.Dust = itemDisplay.Value + dustNum;
            itemDisplay.ChangeValue(dustNum);
            userMapper.UpdateData(user);
            userMapper.CloseConnection();
            
            CardMapper cardMapper = new CardMapper();
            // TODO 修改为当前登录的玩家
            cardMapper.UpdateUserCardCount(currentCard.CardId, 1, currentCard.CardCount);
            cardMapper.CloseConnection();
            
            // 重新渲染
            ShowCollectCards(current, PAGE_SIZE);
            
            // 重新渲染查看的卡牌的信息
            ShowCardDetail(currentCard);
        }

        /// <summary>
        /// 批量分解卡牌
        /// </summary>
        public void OnResolveSurplusCards()
        {
            CardMapper cardMapper = new CardMapper();
            UserMapper userMapper = new UserMapper();
            int dustSum = 0;
            // 遍历玩家的所有数量大于3的卡牌
            // TODO 改为当前登录的用户
            List<CollectCardVO> cardList = cardMapper.ListCollectCardVOByUserIdAndGtCardCount(1,3);
            // 将玩家的所有数量大于3的卡牌数量改为3
            foreach (CollectCardVO card in cardList)
            {
                // 遍历卡牌列表，修改卡牌数量，计算总的尘数量
                cardMapper.UpdateUserCardCount(card.CardId, 1, 3);
                int dustNum = 0;
                if (card.CardRarity == (int)CardRarityEnum.N)
                {
                    dustNum = 10;
                }else if (card.CardRarity == (int)CardRarityEnum.R)
                {
                    dustNum = 30;
                }else if (card.CardRarity == (int)CardRarityEnum.SR)
                {
                    dustNum = 100;
                }else if (card.CardRarity == (int )CardRarityEnum.UR)
                {
                    dustNum = 1000;
                }
                dustSum += dustNum* (card.CardCount - 3);
            }
            // 为玩家新增尘
            // TODO 改为当前登录的用户
            User user = userMapper.GetUserById(1);
            // TODO 改为当前登录的用户
            userMapper.ChangeDustNumByUserId(1 , user.Dust + dustSum);
            // 重新渲染卡牌列表
            ShowCollectCards(current, PAGE_SIZE);
            userMapper.CloseConnection();
            cardMapper.CloseConnection();
            ItemDisplay itemDisplay = DustDisplay.GetComponent<ItemDisplay>();
            itemDisplay.ChangeValue(dustSum);
        }

        public void OnCompoundCard()
        {
            UserMapper userMapper = new UserMapper();
            CardMapper cardMapper = new CardMapper();
            // 让玩家的尘减少
            int dustNum = 0;
            if (currentCard.CardRarity == (int)CardRarityEnum.N)
            {
                dustNum = 50;
            }else if (currentCard.CardRarity == (int)CardRarityEnum.R)
            {
                dustNum = 100;
            }else if (currentCard.CardRarity == (int)CardRarityEnum.SR)
            {
                dustNum = 500;
            }else if (currentCard.CardRarity == (int )CardRarityEnum.UR)
            {
                dustNum = 3000;
            }
            // TODO 改为当前登录的用户
            User user = userMapper.GetUserById(1);
            userMapper.ChangeDustNumByUserId(1 , user.Dust-dustNum);
            // 增加合成的卡牌
            CollectCardVO collectCard = cardMapper.GetCollectCardVOByCardIdAndUserId(currentCard.CardId , 1);
            if (collectCard != null)
            {
                // TODO 改为当前登录的用户
                cardMapper.UpdateUserCardCount(collectCard.CardId, 1, collectCard.CardCount+1);
            }
            else
            {
                // TODO 改为当前登录的用户
                cardMapper.AddCardToUser(currentCard.CardId, 1 , 1);
            }
            // 重新渲染
            ItemDisplay itemDisplay = DustDisplay.GetComponent<ItemDisplay>();
            itemDisplay.ChangeValue(-dustNum);
            ShowCollectCards(current, PAGE_SIZE);
            cardMapper.CloseConnection();
            userMapper.CloseConnection();
            // 重新渲染查看的卡牌的信息
            currentCard.CardCount += 1;
            ShowCardDetail(currentCard);
        }

        public void ClearCollectCards()
        {
            foreach (var entry in CollectCardList)
            {
                Destroy(entry.Value);
            }
            CollectCardList.Clear();
        }

        public void AddCardToDeck(long cardId, string cardName)
        {
            if (DeckCardList.ContainsKey(cardId))
            {
                DeckCardList[cardId]++;
                DeckCardObjectList[cardId].GetComponent<CollectDeckCard>().AddCount();
            }
            else
            {
                DeckCardList.Add(cardId, 1);
                GameObject collectDeckCard = Instantiate(CollectDeckCardPrefab, ScrollContent.transform);
                collectDeckCard.transform.parent = ScrollContent.transform;
                CollectDeckCard card = collectDeckCard.GetComponent<CollectDeckCard>();
                card.SetCardInfo(cardId, cardName, 1);
                DeckCardObjectList.Add(cardId , collectDeckCard);
            }
        }

        public bool IsAddable(long cardId)
        {
            return !DeckCardList.ContainsKey(cardId) || DeckCardList[cardId] < 3;
        }

        public void RemoveCardFromDeck(long cardId, GameObject card)
        {
            if (DeckCardList.ContainsKey(cardId))
            {
                DeckCardList[cardId]--;
            }

            if (DeckCardList[cardId] != 0) return;
            Destroy(card);
            DeckCardList.Remove(cardId);
            DeckCardObjectList.Remove(cardId);
        }

        public void SubmitDeckEdition()
        {
            DeckMapper deckMapper = new DeckMapper();
            deckMapper.DeleteAllCardsFromDeckByDeckId(deckId);
            foreach (var entry in DeckCardList)
            {
                long cardId = entry.Key;
                int cardCount = entry.Value;
                deckMapper.AddCardToDeck(deckId, cardId, cardCount);
            }
            deckMapper.CloseConnection();
        }
        
        public void ShowCardDetail(CollectCardVO card)
        {
            CardDetailCanvas.enabled = true;
            CardDetail cardDetail = CardDetailObject.GetComponent<CardDetail>();
            cardDetail.SetCardInfo(card);
            currentCard = card;
            
            // 设置分解与合成需要展示的数字
            int compoundDustNum = 0;
            if (currentCard.CardRarity == (int)CardRarityEnum.N)
            {
                compoundDustNum = 50;
            }else if (currentCard.CardRarity == (int)CardRarityEnum.R)
            {
                compoundDustNum = 100;
            }else if (currentCard.CardRarity == (int)CardRarityEnum.SR)
            {
                compoundDustNum = 500;
            }else if (currentCard.CardRarity == (int )CardRarityEnum.UR)
            {
                compoundDustNum = 3000;
            }
            CompoundDustNum.text ="- "+ compoundDustNum.ToString();
            
            int resolveDustNum = 0;
            if (card.CardRarity == (int)CardRarityEnum.N)
            {
                resolveDustNum = 10;
            }else if (card.CardRarity == (int)CardRarityEnum.R)
            {
                resolveDustNum = 30;
            }else if (card.CardRarity == (int)CardRarityEnum.SR)
            {
                resolveDustNum = 100;
            }else if (card.CardRarity == (int )CardRarityEnum.UR)
            {
                resolveDustNum = 1000;
            }
            ResolveDustNum.text ="+ "+ resolveDustNum.ToString();
        }

        public void OnExit()
        {
            SubmitDeckEdition();
            GlobalSceneManager.LoadSceneByName("MainScene");
        }
    }
}
